package cn.wolfcode.zookeeper.server;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.ArrayList;
import java.util.List;

//客户端发现服务端信息
public class OrderClientDiscovery {
    //zkServer的连接地址信息
    private String connectStr="lab171:2181,lab172:2181,lab173:2181";
    //客户端连接zkServer的超时时间
    private int sessionTimeOut=2000;
    //zk客户端
    private ZooKeeper client=null;
    //服务器信息存放地址
    private String serverAddr="/servers";
    //存放服务器信息地址列表的信息
    private List<String> orderServerList=new ArrayList<>();

    public OrderClientDiscovery() throws Exception {
        //实例化zk客户端,这里需要指定事件监听
        client=new ZooKeeper(connectStr, sessionTimeOut, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                //连接成功状态
                if(event.getState()==Event.KeeperState.SyncConnected){
                    //对于指定路径的事件监听
                    if(serverAddr.equals(event.getPath())){
                        //监听子节点改变状态,子节点的数量增加或者减少
                        if(event.getType()==Event.EventType.NodeChildrenChanged){
                            try {
                                //调用业务处理方法
                                getOrderServerList();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
    }

    public void getOrderServerList() throws Exception{
        //获取到所有的子节点列表, 其中true是保持监听状态,使用创建zkClient的默认事件监听程序
        List<String> nodeList =  client.getChildren(serverAddr,true);
        //临时列表,用于存放对应的服务器信息
        List<String> temp=new ArrayList<>();
        for (String node : nodeList) {
            //获取节点的数据, 地址+端口
            byte[] data = client.getData(serverAddr+"/"+node,null,null);
            temp.add(new String(data));
        }
        //更新成员变量服务器列表信息
        orderServerList=temp;
        System.out.println("更新后的服务器列表为:"+orderServerList);
    }

    public static void main(String[] args) throws Exception {
        OrderClientDiscovery orderClient = new OrderClientDiscovery();
        orderClient.getOrderServerList();
        System.out.println("客户端启动完成,随时监听服务器列表的改变信息");
        Thread.sleep(Long.MAX_VALUE);
    }
}
